package com.yunban.project.api.text_check.task;

import com.yunban.project.api.text_check.service.impl.CorrectionFactory;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * @author: lijiajun
 * @date: 2024-12-04
 * @version: 1.0
 */
@Component
@Configuration
public class TextCorrectionJob {

    @Resource
    private CorrectionFactory correctionFactory;

    /**
     * 每隔500毫秒执行一次文本纠错
     */
    @Scheduled(fixedRate = 500)
    @Async("correctAsyncServiceExecutor")
    public void executeTextCorrection() {
        // 纠错
        this.correctionFactory.correctionTask();
    }

    public static String encrypt(String text, String secretKey) {
        try {
            // 确保密钥长度符合AES-256要求，即32字节
            if (secretKey.length() != 32) {
                throw new IllegalArgumentException("Secret key must be 32 bytes long for AES-256");
            }

            // 16字节IV
            String iv = "1234567890123456";
            byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
            byte[] ivBytes = iv.getBytes(StandardCharsets.UTF_8);

            // 创建密钥和IV对象
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

            // 初始化Cipher对象
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

            // 加密
            byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));

            // 返回Base64编码的加密结果
            String s = Base64.getEncoder().encodeToString(encryptedBytes);
            return s;
//            System.out.println(s);
//            // url_encode
//            return URLEncoder.encode(s, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public static void main(String[] args) {
        //             5d7e8f9a-bcde-4fgh-8ijk-lmnopqrstuvw17423790165d7e8f9a-bcde-4fgh-8ijk-lmnopqrstuvw
        String text = "5d7e8f9a-bcde-4fgh-8ijk-lmnopqrstuvw17423790165d7e8f9a-bcde-4fgh-8ijk-lmnopqrstuvw";
        // php  AsSUT5mbrTQPxILx1VVpwFICXo8TRB1ZJmDO83KwAdI1k0DH5owrU0vE3q9jk4e5RCkXQhJtDSWxegGuF5kysOBka5QpxdHn/UHsfR+MKRSLSg3AvsfmVO6akfSt2l0H
        // java AsSUT5mbrTQPxILx1VVpwFICXo8TRB1ZJmDO83KwAdL/XAkeVlQyN2PHQ5uK5E5vww/di2xQSW/XAQDYI+HNktXiYDotjujQofkt+dqHrEIZBJevG5IVSPafEDarF+Bd
        System.out.println(TextCorrectionJob.encrypt(text, "Vz5jX8qN4bPwM7yL9vEr2kTg6hZi0oDf"));
    }
}